package com.jzzzb.distributedlock.config;

import com.jzzzb.distributedlock.aspect.DistributedLockAspect;
import com.jzzzb.distributedlock.redis.IRedissonService;
import com.jzzzb.distributedlock.redis.RedissonService;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.util.StringUtils;


/**
 * 分布式锁自动装配类
 *
 * @author zhangbin
 * @date 2025/02/22
 */
@Configuration
@ConditionalOnBean(ConfigMarker.class) // 只有当IOC容器中有 ConfigMarker bean 此配置类才生效 (@EnableDistributedLock开启)
@EnableAspectJAutoProxy
@EnableConfigurationProperties(value = RedisClientConfigProperties.class)
public class DistributedLockAutoConfiguration {

    @Bean("redissonClient")
    public RedissonClient redissonClient(RedisClientConfigProperties properties) {
        Config config = new Config();
        config.useSingleServer()
                .setAddress("redis://" + properties.getHost() + ":" + properties.getPort())
                .setConnectionPoolSize(properties.getPoolSize())
                .setConnectionMinimumIdleSize(properties.getMinIdleSize())
                .setIdleConnectionTimeout(properties.getIdleTimeout())
                .setConnectTimeout(properties.getConnectTimeout())
                .setRetryAttempts(properties.getRetryAttempts())
                .setRetryInterval(properties.getRetryInterval())
                .setPingConnectionInterval(properties.getPingInterval())
                .setKeepAlive(properties.isKeepAlive());

        if (StringUtils.hasText(properties.getPassword())) {
            config.useSingleServer().setPassword(properties.getPassword());
        }
        return Redisson.create(config);
    }

    @Bean
    public DistributedLockAspect distributedLockAspect() {
        return new DistributedLockAspect();
    }

    @Bean
    public IRedissonService redissonService() {
        return new RedissonService();
    }

}
